/*
 * @Author: xiaosihan
 * @Date: 2023-03-08 00:01:34
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-01-07 20:42:28
 */





import utils from "@utils";
import editor3DStore from "@views/editor3D/editor3DStore";
import { LabelData } from "@views/type";
import { autorun } from "mobx";
import { Intersection, Raycaster, Sprite } from "three";
import SpriteText2 from "three-base/SpriteText2";
import threeLoader from "three-base/threeLoader";

// 标签
export default class Label extends Sprite {

    constructor() {
        super();
        this.material.map = this.texture;
        this.material.transparent = true;
        this.material.alphaTest = 0.01;
        this.updata();

        //three事件
        this.userData = {
            cursor: "pointer",
            enableEvent: true,
        };
        this.addEventListener("click", (e: any) => {
            editor3DStore.setLookLabelId(this.uuid);
            const customEvent = new CustomEvent("selectLabelDatatId", { detail: { lookLabelId: this.uuid } });
            window.dispatchEvent(customEvent);
        });
        this.addEventListener("mouseenter", (e: any) => {
            this.scale.set(21, 21, 21);
            this.allTextLabel.visible = true;
        });
        this.addEventListener("mouseleave", (e: any) => {
            this.scale.set(20, 20, 20);
            this.allTextLabel.visible = false;
        });
    }

    userData = {
        cursor: "pointer",
        enableEvent: true,
    };

    // 图标
    iconImg = (() => {
        const img = new Image();
        img.src = "";
        return img;
    })();

    // 文本背景
    textContainer = (() => {
        const img = new Image();
        img.src = "";
        return img;
    })();


    canvas = (() => {
        const canvas = document.createElement("canvas");
        canvas.width = 1024;
        canvas.height = 1024;
        return canvas;
    })();

    allTextLabel = (() => {
        const allTextLabel = new SpriteText2("123");
        allTextLabel.position.set(0, 0.21, 0);
        allTextLabel.visible = false;
        allTextLabel.backgroundColor = "#6DB52D";
        allTextLabel.material.sizeAttenuation = true;
        allTextLabel.material.depthTest = false;
        allTextLabel.fontSize = 200;
        allTextLabel.borderRadius = 1;
        //@ts-ignore
        allTextLabel.padding = [2, 2];
        allTextLabel.scale.multiplyScalar(0.01);
        allTextLabel.renderOrder = 10;

        this.add(allTextLabel);
        return allTextLabel;
    })();

    context = this.canvas.getContext("2d")!;

    texture = threeLoader.getTexture(this.canvas);

    data: LabelData = {
        id: "",  // id
        name: "", // 备用字段
        floorId: "",//楼层id
        positionX: 0,  // x坐标
        positionY: 0,  // y坐标
        positionZ: 0,  // z坐标
        heading: 0,
        pitch: 0,
        roll: 0,
        icon: "", // 图标
        textContainer: "" // 标签文本
    }

    // 设置数据
    setData(data: LabelData) {
        const { id, name, positionX, positionY, positionZ, icon, textContainer } = data;

        let needUpdata = false;

        if (
            this.uuid !== String(id) ||
            !this.iconImg.src.includes(icon) ||
            !this.textContainer.src.includes(textContainer) ||
            this.allTextLabel.text !== name
        ) {
            needUpdata = true;
        }

        this.uuid = String(id);
        this.position.set(positionX, positionY, positionZ);
        this.iconImg.src = icon;
        this.textContainer.src = textContainer;

        this.allTextLabel.text = name;
        this.allTextLabel.scale.multiplyScalar(0.02);

        this.data = data;

        if (needUpdata) {
            this.updata();
        }
    }

    async updata() {
        //绘制背景
        this.context.clearRect(0, 0, 1024, 1024);

        while (!this.iconImg.complete && !this.textContainer.complete) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }

        // 设置大小
        this.scale.set(20, 20, 20);

        // this.context.fillStyle = "#ffffff22";
        // this.context.fillRect(0, 0, 1024, 1024);

        //绘制背景
        this.context.drawImage(this.iconImg, 0, 0, this.iconImg.naturalWidth, this.iconImg.naturalHeight, (1024 - 140) / 2, 512 - 140 - 20, 140 / this.iconImg.naturalHeight * this.iconImg.naturalWidth, 140);

        this.context.drawImage(this.textContainer, 0, 0, this.textContainer.naturalWidth, this.textContainer.naturalHeight, (1024 - 140) / 2 + 112, 512 - 140 - 20, 140 / this.textContainer.naturalHeight * this.textContainer.naturalWidth, 140);

        // 绘制标题
        this.context.fillStyle = "#ffffff";
        this.context.font = '70px serif';// 设置字体大小
        this.context.textAlign = "left";
        this.context.textBaseline = "top";

        // 字符分隔为数组
        var arrText = this.data.name.split('');
        var line = '';
        // 文字自动换行计算
        for (var n = 0; n < arrText.length; n++) {
            var metrics = this.context.measureText(line + arrText[n]);
            var testWidth = metrics.width;
            if ((testWidth > 300 && n > 0)) {
                line += "...";
                break;
            } else {
                line += arrText[n];
            }
        }

        this.context.fillText(line, 580, 370);

        this.texture.needsUpdate = true;

        this.dispatchEvent({ type: "loaded" } as never);
    }

    //鼠标拾取计算
    raycast(raycaster: Raycaster, intersects: Intersection[]) {

        let intersect: Intersection[] = [];
        super.raycast(raycaster, intersect);
        let inte = intersect[0];

        if (inte && (inte.uv!.x > 0.43 && inte.uv!.x < 1.0) && (inte.uv!.y > 0.517 && inte.uv!.y < 0.656)) {
            intersects.push(inte);
        }

    }

}

